package com.example.influxdb01.service;

import com.example.influxdb01.utils.CSVWriter;
import com.example.influxdb01.utils.PropertiesReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author yihao
 * @description 解析配置文件 初始化相关参数，拿到内容后写csv文件
 * @time 2022/04/26 11:32:18
 */
public class PackageInfoWriteService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CSVWriter.class);

    private static String packageInfoFile;

    private static String[] fileHeader;

    private static String queryStartTime;

    private static String queryEndTime;
    /**
     * 是否将所有数据生成一个文件 默认生成一个文件，可以配置分包输出
     */
    private static boolean compound;
    /**
     * 最终生成的所有包合成一个csv文件的名称
     */
    private static String compoundFileName;
    /**
     * 这里要保证集合的顺序，所以使用这个实现类
     */
    private static Map<String, Integer> packagesWithParamCount = new LinkedHashMap<>();
    /**
     * 对原结果集按时间当主键，参数名称当字段转置后的文件头,也就time加上各个包下需要查询的参数
     */
    private static Map<String,String[]> resultFileHeaders = new LinkedHashMap<>();;

    private static String[] params;

    static {
        try {
            Properties prop = PropertiesReader.readProperties("src/main/resources/param.properties");
            packageInfoFile = prop.getProperty("csvfile.output.path");
            String headers = prop.getProperty("packageInfo.header");
            fileHeader = headers.split(",");

            String[] packages = prop.getProperty("packages").split(",");
            if (packages.length % 2 != 0) {
                throw new IllegalStateException("配置文件格式不对");
            }

            //拿到包及对应需要获取的参数个数
            Integer count = 0;
            while (count < packages.length) {
                packagesWithParamCount.put(packages[count], Integer.valueOf(packages[count + 1]));
                //先把文件头对应的包名放进去
                resultFileHeaders.put(packages[count], null);
                count += 2;
            }
            LOGGER.info("packages: {}",packagesWithParamCount);

            //拿到所有需要获取的参数
            params = prop.getProperty("paramters").split(",");
            LOGGER.info("params:{}", Arrays.toString(params));

            Iterator<String> iterator = packagesWithParamCount.keySet().iterator();
            int num = 0;
            int currentParaNum = 0;
            while (iterator.hasNext()) {
                String packageName = iterator.next();
                currentParaNum += packagesWithParamCount.get(packageName);

                //给head数组前加上time 这里的嵌套声名是把只读集合变成读写集合
                ArrayList<String> strings = new ArrayList<>(Arrays.asList(Arrays.copyOfRange(params, num, currentParaNum)));
                strings.add(0,"time");

                resultFileHeaders.put(packageName, strings.toArray(new String[packagesWithParamCount.get(packageName)]));
                num += currentParaNum;
                LOGGER.info("resultFile headers packageName:{}, headers:{}", packageName,Arrays.toString(resultFileHeaders.get(packageName)));

            }

            //获取查询的时间起点和结束
            queryStartTime = prop.getProperty("query.startTime");
            queryEndTime = prop.getProperty("query.endTime");

            //是否分包
            compound = prop.getProperty("csvfile.isCompound").equals("2") ? true : false;

            //获取目标文件的名称
            compoundFileName = prop.getProperty("csvfile.name");


        } catch (Exception e) {
            LOGGER.error("",e);
        }

        // 创建目录
        File targetDir = new File(packageInfoFile);
        if( !targetDir.exists() ) {
            LOGGER.warn("csv文件父目录不存在，即将创建...");
            targetDir.mkdirs();
        }
    }


    public void wirte(List<String[]> content,String fileName,String[] fileHeader) {
        try {
            CSVWriter.write(packageInfoFile +"/"+fileName+".csv", fileHeader, content);
        } catch (IOException e) {
            LOGGER.error("写csv文件出现问题",e);
        }
    }

    public static Map<String, Integer> getPackagesWithParamCount() {
        return packagesWithParamCount;
    }

    public static void setPackagesWithParamCount(Map<String, Integer> packagesWithParamCount) {
        PackageInfoWriteService.packagesWithParamCount = packagesWithParamCount;
    }

    public static String[] getParams() {
        return params;
    }

    public static void setParams(String[] params) {
        PackageInfoWriteService.params = params;
    }

    public static String[] getFileHeader() {
        return fileHeader;
    }

    public static void setFileHeader(String[] fileHeader) {
        PackageInfoWriteService.fileHeader = fileHeader;
    }

    public static Map<String, String[]> getResultFileHeaders() {
        return resultFileHeaders;
    }

    public static void setResultFileHeaders(Map<String, String[]> resultFileHeaders) {
        PackageInfoWriteService.resultFileHeaders = resultFileHeaders;
    }

    public static String getQueryStartTime() {
        return queryStartTime;
    }

    public static void setQueryStartTime(String queryStartTime) {
        PackageInfoWriteService.queryStartTime = queryStartTime;
    }

    public static String getQueryeEndTime() {
        return queryEndTime;
    }

    public static void setQueryeEndTime(String queryeEndTime) {
        PackageInfoWriteService.queryEndTime = queryeEndTime;
    }

    public static String getCompoundFileName() {
        return compoundFileName;
    }

    public static void setCompoundFileName(String compoundFileName) {
        PackageInfoWriteService.compoundFileName = compoundFileName;
    }

    public static boolean isCompound() {
        return compound;
    }

    public static void setCompound(boolean compound) {
        PackageInfoWriteService.compound = compound;
    }
}
